package com.example.simin_manage.admim.controller;
import com.example.simin_manage.admim.dto.Response;
import com.example.simin_manage.admim.dto.SysDeptVO;
import com.example.simin_manage.admim.service.SysDeptService;
import com.example.simin_manage.entity.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
 * @description:
 * @author: panpan
 * @time: 2025/9/14
 */


@RestController
@RequestMapping("/api/admin/depts")
public class SysDeptController {

    @Autowired
    private SysDeptService deptService;

    // 查询所有部门
    @GetMapping
    public Response getAllDepts() {
        List<SysDeptVO> depts = deptService.listDeptsWithLeaderName();
        return new Response(200, "查询成功", depts);
    }

    // 新增部门
    @PostMapping
    public Response addDept(@RequestBody SysDept dept) {
        boolean ok = deptService.save(dept);
        return ok ? new Response(200, "新增成功", dept) : new Response(500, "新增失败", null);
    }
//    列出部门
    @GetMapping("/list")
    public Response listAllDepts() {
        List<SysDept> depts = deptService.list();
        return new Response(200, "查询成功", depts);
    }
    // 根据 ID 查询部门
    @GetMapping("/{id}")
    public Response getDept(@PathVariable Long id) {
        SysDept dept = deptService.getById(id);
        return dept != null ? new Response(200, "查询成功", dept) : new Response(404, "部门不存在", null);
    }

    // 更新部门
    @PutMapping("/{id}")
    public Response updateDept(@PathVariable String id, @RequestBody SysDept dept) {
        dept.setId(Long.parseLong(id));  // 转成 Long
        if(dept.getLeaderId() != null) {
            // leaderId 也可以用 String 前端传回来，再转换
            dept.setLeaderId(Long.parseLong(String.valueOf(dept.getLeaderId())));
        }
        boolean ok = deptService.updateById(dept);
        return ok ? new Response(200, "修改成功", dept) : new Response(500, "修改失败", null);
    }

    // 删除部门
    @DeleteMapping("/{id}")
    public Response deleteDept(@PathVariable Long id) {
        boolean ok = deptService.removeById(id);
        return ok ? new Response(200, "删除成功", null) : new Response(500, "删除失败", null);
    }
}
